package com.sst.common.Test.DataImport;

import com.sst.common.utils.RandomNum;
import com.sst.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 第一次插入151s
 * 第二次插入8307s
 */

public class Insert {
    public static void main(String[] args) {
        Insert.createData();
    }

    public static void createData() {
        // 开始时间
        long startTime = System.currentTimeMillis();
        // 创建线程池，线程核心数量为100
        ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        // 分50次插入数据
        int totalPageNo = 81;
        // 每是2w条数据
        int pageSize = 13258;
        // 保证线程的原子性
        AtomicInteger atomicInt = new AtomicInteger();
        for (int currentPageNo = 0; currentPageNo < totalPageNo; currentPageNo++) {
            List<Hero> heroList = new ArrayList<>();
            // 开启线程
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    for (int i = 1; i <= pageSize; i++) {
                        Hero hero = new Hero();
                        hero.setId(StringUtils.getUUID());
                        hero.setHeroName(RandomNum.getRandomName());
                        hero.setAge(RandomNum.getRandomNums(90));
                        hero.setWeapon(RandomNum.getRandomWeapon());
                        hero.setCity(RandomNum.getRandomCity());
                        heroList.add(hero);
                    }
                    try {
                        atomicInt.addAndGet(HeroBatchHandler.batchSave(heroList, Thread.currentThread().getName()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 入库的数据达到一百万条的时候就会有个统计.
                    if (atomicInt.get() == (totalPageNo * pageSize)) {
                        // 如果有一百万的时候.就会在这里有个结果
                        System.out.println("同步数据到db，它已经花费 " + ((System.currentTimeMillis() - startTime) / 1000) + "  秒");
                    }
                }
            };
//			try {
//				Thread.sleep(5);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
            // 执行线程
            pool.execute(run);
        }

    }
}
